/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yiimanager Software LLC
 */
!function (global, top) {
    "use strict";
    global.ym2App.controller("ym2.ctrl.upload.add", [
        "$scope",
        "$http",
        "$timeout",
        "Upload",
        "ym2Encrypt",
        "ym2",
        "lodash",
        "ymSpinner",
        function ($scope, $http, $timeout, Upload, ym2Encrypt, ym2, lodash, ymSpinner) {
            var topSweetAlert = top.sweetAlert;
            var topLayer = top.layui.layer;
            var topToastr = top.toastr;

            var httpSuccessCode = ym2.getHttpSuccessCode();
            var httpFailureCode = ym2.getHttpFailureCode();
            var httpUnauthorizedCode = ym2.getHttpUnauthorizedCode();
            var ajaxIdentity = ym2.getHttpAjaxIdentity();
            var adminRouteLogin = ym2.getAdminRouteLogin();

            var WAIT_UPLOAD = "WAIT_UPLOAD";//待上传
            var UPLOADING = "UPLOADING";//上传中
            var UPLOADED = "UPLOADED";//已完成
            var UPLOAD_ERROR = "UPLOAD_ERROR";//已失败

            var MAX_UPLOAD_COUNT = 20;//单次最大上传数量

            //初始化
            var initializeState = {
                status: WAIT_UPLOAD,
                totalCount: 0,
                successCount: 0,
                errorCount: 0,
            };
            $scope._initScope = function () {
                // local/cloud
                $scope.uploadWay = "local";
                $scope.cloudFileLink = "";
                $scope.uploadList = [];
                $scope.uploadState = Object.assign({}, initializeState);
            };
            $scope._initScope();
            //文件选择
            $scope.fileSelect = function (files) {
                if ($scope.uploadState.status !== WAIT_UPLOAD) {
                    return;
                }
                if (files && files.length) {
                    var tmpList = [];
                    for (var i = 0; i < files.length; i++) {
                        tmpList.push({
                            etag: $scope._getEtag(files[i]),
                            file: files[i],
                            name: files[i].name,
                            _size: files[i].size,
                            size: ym2.asShortSize(files[i].size),
                            _loadedSize: 0,
                            loadedShortSize: 0,
                            dasharray: 0,
                            processRate: 0,
                            uploadStatus: WAIT_UPLOAD,
                            uploadError: "",
                        });
                    }

                    tmpList = lodash.uniqBy($scope.uploadList.concat(tmpList), "etag");
                    $scope.uploadList = tmpList;

                    var currentItem;
                    var totalCount = 0;
                    var successInitCount = 0;
                    var errorInitCount = 0;
                    for (var j = 0; j < tmpList.length; j++) {
                        currentItem = tmpList[j];
                        totalCount++;
                        if (currentItem.uploadStatus === UPLOADED) {
                            successInitCount++;
                        }
                        if (currentItem.uploadStatus === UPLOAD_ERROR) {
                            errorInitCount++;
                        }
                    }

                    $scope.uploadState.totalCount = totalCount;
                    $scope.uploadState.successCount = successInitCount;
                    $scope.uploadState.errorCount = errorInitCount;
                }
            };
            //移除上传项
            $scope.removeItem = function (index) {
                if (!$scope.uploadList.length) {
                    return;
                }
                if ($scope.uploadState.status === UPLOADING) {
                    return;
                }
                if (index === undefined) {
                    $scope.uploadList = [];
                    $scope.uploadState = Object.assign({}, initializeState);
                } else {
                    var tmpItem = $scope.uploadList[index];
                    $scope.uploadList.splice(index, 1);
                    if (tmpItem) {
                        $scope.uploadState.totalCount--;
                        if (tmpItem.uploadStatus === UPLOADED) {
                            $scope.uploadState.successCount--;
                        } else if (tmpItem.uploadStatus === UPLOAD_ERROR) {
                            $scope.uploadState.errorCount--;
                        }
                        if ($scope.uploadState.totalCount <= 0) {
                            $scope.uploadState.status = WAIT_UPLOAD;
                        }
                    }
                }
            };
            //点击上传
            $scope.uploadFiles = function () {
                var tmpList = $scope.uploadList;
                if (!tmpList.length) {
                    return;
                }
                if ($scope.uploadState.status !== WAIT_UPLOAD) {
                    return;
                }
                if (tmpList.length > MAX_UPLOAD_COUNT) {
                    var moreCount = tmpList.length - MAX_UPLOAD_COUNT;
                    topLayer.alert("单次最大上传文件数量: " + MAX_UPLOAD_COUNT + "个, 当前数量已超出: " +  moreCount + "个, 请删除超出文件后重试!");
                    return;
                }
                var currentItem;
                for (var i = 0; i < tmpList.length; i++) {
                    currentItem = tmpList[i];
                    if (currentItem.uploadStatus === WAIT_UPLOAD) {
                        if ($scope.uploadState.status !== UPLOADING) {
                            $scope.uploadState.status = UPLOADING;
                        }
                        $scope._setUploadStatus(i, UPLOADING);
                        $scope._upload(currentItem, i);
                    }
                }
            };
            //获取etag
            $scope._getEtag = function($file) {
                return ym2Encrypt.md5($file.name + $file.size + $file.type + $file.lastModified)
            };
            //上传逻辑
            $scope._upload = function (fileItem, fileIndex) {
                Upload.upload({
                    url: "/__upload/chunk",
                    data: {
                        file: fileItem.file,
                        etag: fileItem.etag,
                    },
                    resumeSizeUrl: "/__upload/resume?etag=" + fileItem.etag,
                    resumeSizeResponseReader: function(data) {
                        return parseFloat(data.size);
                    },
                    resumeChunkSize: "2mb",
                }).then(function (resp) {
                    $scope._moveFile(fileItem, fileIndex);
                }, function (resp) {
                    $scope._setUploadStatus(fileIndex, UPLOAD_ERROR, "控制台查看错误信息!");
                    console.error('Error status: ' + resp.status);
                }, function (evt) {
                    var loaded = evt.config._end || evt.loaded;
                    var total = evt.total;
                    if (loaded > total) loaded = evt.total;
                    var progressPercentage = parseInt(100 * loaded / total);
                    if (progressPercentage >= 100) progressPercentage = 99;
                    $scope._showUploadProcess(loaded, progressPercentage, fileIndex);
                });
            };
            //设置上传状态
            $scope._setUploadStatus = function (index, status, error) {
                $scope.uploadList[index].uploadStatus = status;
                if (error) {
                    $scope.uploadList[index].uploadError = error;
                }
                if (status === UPLOADED) {
                    $scope.uploadState.successCount++;
                } else if (status === UPLOAD_ERROR) {
                    $scope.uploadState.errorCount++;
                }
                if ($scope.uploadState.successCount + $scope.uploadState.errorCount === $scope.uploadState.totalCount) {
                    $scope.uploadState.status = UPLOADED;
                }
            };
            //上传进度展示
            var CR = 11;
            var CL = 2 * Math.PI * CR;
            $scope._showUploadProcess = function (loaded, percentage, fileIndex) {
                $scope.uploadList[fileIndex].dasharray = Math.floor(percentage / 100 * CL);
                $scope.uploadList[fileIndex].processRate = percentage;
                $scope.uploadList[fileIndex]._loadedSize = loaded;
                $scope.uploadList[fileIndex].loadedShortSize = ym2.asShortSize(loaded);
            };
            //上传完成,移动文件
            $scope._moveFile = function (fileItem, fileIndex) {
                var bodyParam = {
                    name: fileItem.name,
                    etag: fileItem.etag,
                    classify: $scope.classify,
                };
                bodyParam[ajaxIdentity] = 1;
                $http.post("/__upload/move", bodyParam).then(function (result) {
                    var data = result.data;
                    switch (data.code) {
                        case httpSuccessCode:
                            $scope.uploadList[fileIndex].dasharray = CL;
                            $scope.uploadList[fileIndex].processRate = 100;
                            $scope.uploadList[fileIndex]._loadedSize = fileItem.file.size;
                            $scope.uploadList[fileIndex].loadedShortSize = ym2.asShortSize(fileItem.file.size);
                            $scope._setUploadStatus(fileIndex, UPLOADED);
                            break;
                        case httpUnauthorizedCode:
                            $scope._setUploadStatus(fileIndex, UPLOAD_ERROR, data.msg);
                            // 授权失效, 去登录
                            ym2.swal.timer(
                                topSweetAlert,
                                data.msg,
                                "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open(adminRouteLogin, "_self");
                                },
                                3000
                            );
                            break;
                        case httpFailureCode:
                        default:
                            $scope._setUploadStatus(fileIndex, UPLOAD_ERROR, data.msg);
                    }

                }, function (error) {
                    $scope._setUploadStatus(fileIndex, UPLOAD_ERROR, error.data || "未知错误;请查看控制台!");
                    console.log(error);
                });
            };
            //云文件提交
            $scope.cloudFileSubmit = function () {
                var cloudLink = $scope.cloudFileLink;
                if (!cloudLink) {
                    topToastr.info("请填写文件链接路径!");
                    return;
                }
                if (
                    cloudLink.substr(0, 4).toLowerCase() !== "http"
                    && cloudLink.substr(0, 2).toLowerCase() !== "//"
                ) {
                    topToastr.info("文件路径格式错误,请重新填写!");
                    return;
                }
                var bodyParam = {
                    file: cloudLink,
                    classify: $scope.classify,
                };
                bodyParam[ajaxIdentity] = 1;
                var flag = ymSpinner.show();
                $http.post("/__upload/cloud-file", bodyParam).then(function (result) {
                    ymSpinner.hide(flag);

                    var data = result.data;
                    switch (data.code) {
                        case httpSuccessCode:
                            $scope.cloudFileLink = "";
                            topToastr.success("上传成功!");
                            break;
                        case httpUnauthorizedCode:
                            // 授权失效, 去登录
                            ym2.swal.timer(
                                topSweetAlert,
                                data.msg,
                                "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open(adminRouteLogin, "_self");
                                },
                                3000
                            );
                            break;
                        case httpFailureCode:
                        default:
                            topToastr.error(data.msg);
                    }

                }, function (error) {
                    console.log(error);
                    ymSpinner.hide(flag);
                    topToastr.error(error.data || "请打开控制台查看错误信息!");
                });

            };

        }
    ]).directive("ym2Tooltip", ["layui", function (layui) {
        return {
            restrict: "A",
            link: function (scope, element, attr) {
                element.on("mouseover", function () {
                    layui.layer.tips(scope.$eval(attr.ym2Tooltip), this, {
                        tips: [4, "#F56692"],
                        closeBtn: 1,
                    });
                });
            },

        };
    }]).filter("asShortTime", ["ym2", function (ym2) {
        // 过滤器:转时间短语
        return function (value, defaultVal) {
            if (!value) {
                return defaultVal || "00:00:00 000";
            }

            return ym2.asShortTime(value);
        };
    }]);
}(window, top);